
#include "cs1237_3line_bus.h"

// io设置在bsp_io_init()中
static void init(void *base)
{
    cs1237_bus_handle_t *t = (cs1237_bus_handle_t *)base;
    hal_pin_reset(&t->io_clk);
    hal_pin_set(&t->io_out);
}

static void clock(void *base, uint16_t time)
{
    cs1237_bus_handle_t *t = (cs1237_bus_handle_t *)base;
    hal_pin_set(&t->io_clk);
    hal_delay_us(time);
    hal_pin_reset(&t->io_clk);
    hal_delay_us(time);
}

static void set_dir(void *base, uint8_t dir)
{
    cs1237_bus_handle_t *t = (cs1237_bus_handle_t *)base;
    if(dir==CS1237_DATA_DIR_IN) //3线通讯，将out引脚开漏
        hal_pin_set(&t->io_out);
    // CS1237_DATA_DIR_OUT 模式不需要设置
}

static void write_bit(void *base, uint8_t bit)
{
    cs1237_bus_handle_t *t = (cs1237_bus_handle_t *)base;
    hal_pin_write(&t->io_out, !bit); //需要取反
}

static uint8_t read_bit(void *base)
{
    cs1237_bus_handle_t *t = (cs1237_bus_handle_t *)base;
    return hal_pin_read(&t->io_in);
}

static void int_enable(void *base, uint8_t enable)
{
    cs1237_bus_handle_t *t = (cs1237_bus_handle_t *)base;
    if(enable==0)
        nvic_irq_disable(t->irqn);
    else
        nvic_irq_enable(t->irqn, 5, 0);
}

cs1237_bus_t cs1237_3line_bus = {
    .init = init,
    .clock = clock,
    .set_dir = set_dir,
    .write_bit = write_bit,
    .read_bit = read_bit,
    .int_enable = int_enable,
};